layui.config({
    base : "../static/js/"
}).extend({
    "address" : "address"
})
layui.use(['form','layer','table','jquery','address','tablePlug'],function(){
    var form = layui.form
        layer = parent.layer === undefined ? layui.layer : top.layer,
        table = layui.table,
        $ = layui.jquery,
        tablePlug = layui.tablePlug,
        address = layui.address;
    
    //获取省信息
    address.provinces();
    
  //企业列表
    var tableIns = table.render({
    	 elem: '#gridList',
         method: 'post',
         url : '../allocatedlist/enterpriseGrid?orderId='+parent.$('#orderId').val(),
         cellMinWidth : 95,
         page : true,
         loading: true,
         sortType: 'server', 
         id: 'gridListTable',
         done: function (res) {
//        	 table.reload('userListTable', {});
        	 console.log(res.count);
        	 $("#count").val(res.count);
        	 if($('#isAll').val()){
        		 $("#lableNum").html('已勾选'+res.count+'个企业');
        	 }else{
        		 $("#lableNum").html('已勾选'+table.checkStatus('gridListTable').data.additional.length+'个企业');
        	 }
        		 var tableView = this.elem.next();
             var totalRow = tableView.find('.layui-table-total');
             var limit = this.page ? this.page.limit : this.limit;
             layui.each(totalRow.find('td'), function (index, tdElem) {
               tdElem = $(tdElem);
               var text = tdElem.text();
               if (text && !isNaN(text)) {
                 text = (parseFloat(text) / limit).toFixed(2);
                 tdElem.find('div.layui-table-cell').html(text);
               }
             });
           },
         checkStatus: {
        	 primaryKey: 'id'
         },
         cols : [[
        	 {type:'checkbox'},
             {field: 'id', title: '序号', minWidth:50, align:"center"},
             {field: 'province', title: '省份', minWidth:50, align:"center"},
             {field: 'cityName', title: '地市名称', minWidth:50, align:"center"},
             {field: 'companyName', title: '公司名称', minWidth:100, align:"center"},
             {field: 'industry', minWidth:100, title: '行业', align:'center'},
             {field: 'state', minWidth:50, title: '状态', align:'center'},
             {field: 'legal', minWidth:50, title: '法人', align:'center'},
             {field: 'registered', minWidth:50, title: '注册资本', align:'center'},
             {field: 'telephone', minWidth:50, title: '联系电话', align:'center'},
             {field: 'address', minWidth:100, title: '企业地址',  align:'center'},
             {field: 'website', minWidth:100, title: '企业网址',  align:'center'},
             {field: 'email', minWidth:80, title: '企业邮箱',  align:'center'},
             {field: 'develop', minWidth:80, title: '发展状态',  align:'center'},
             {field: 'scope', minWidth:100, title: '经营范围',  align:'center'}
         ]]
    });
    
    form.on('switch(isAll)', function(data){
  	  if(this.checked){
  		  $("#isAll").val('true');
  		  $("#lableNum").html('已勾选'+$("#count").val()+'个企业');
  	  }else{
  		$("#isAll").val('');
  		 var checkStatus = table.checkStatus('gridListTable');
    	 $("#lableNum").html('已勾选'+checkStatus.data.additional.length+'个企业');
    	 var num1 = 0;
     	for (var key in users) {
     		if( users[key]){
             num1 += parseInt(users[key]);  
     	}
         }
     	 if(num1>$("#lableNum").html().substring($("#lableNum").html().indexOf('选')+1,$("#lableNum").html().indexOf('个'))){
     		 for (var key in users) {
     	    		if( users[key]){
     	    			 delete users[key];  
     	    	}
     	        }
     		 table.reload('userListTable', {});
     	 }
  	  }
  	}); 
    
    form.on('select(industry)', function(data){
		var industry = $("#industry").find("option:selected").val();
		form.render('select'); //这个很重要
		var index = layer.msg('查询中，请稍候',{icon: 16,time:false,shade:0.8});
    	setTimeout(function(){
    		table.reload("gridListTable",{
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                where: {
                	"industry": industry  //搜索的关键字
                }
            });
			layer.close(index);
		},2000);
	});
    
    form.on('select(develop)', function(data){
		var develop = $("#develop").find("option:selected").val();
		form.render('select'); //这个很重要
		var index = layer.msg('查询中，请稍候',{icon: 16,time:false,shade:0.8});
    	setTimeout(function(){
    		table.reload("gridListTable",{
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                where: {
                	"develop": develop  //搜索的关键字
                }
            });
			layer.close(index);
		},2000);
	});
    
    form.on('select(type)', function(data){
		var type = $("#type").find("option:selected").val();
		form.render('select'); //这个很重要
		var index = layer.msg('查询中，请稍候',{icon: 16,time:false,shade:0.8});
    	setTimeout(function(){
    		table.reload("gridListTable",{
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                where: {
                	"type": type  //搜索的关键字
                }
            });
			layer.close(index);
		},2000);
	});
    
    form.on('select(scale)', function(data){
		var scale = $("#scale").find("option:selected").val();
		form.render('select'); //这个很重要
		var index = layer.msg('查询中，请稍候',{icon: 16,time:false,shade:0.8});
    	setTimeout(function(){
    		table.reload("gridListTable",{
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                where: {
                	"scale": scale  //搜索的关键字
                }
            });
			layer.close(index);
		},2000);
	});

    //搜索
    $(".search_btn").on("click",function(){
    	var index = layer.msg('查询中，请稍候',{icon: 16,time:false,shade:0.8});
        if($(".searchVal").val() != ''){
        	setTimeout(function(){
        		table.reload("gridListTable",{
                    page: {
                        curr: 1 //重新从第 1 页开始
                    },
                    where: {
                    	companyName: $(".searchVal").val()  //搜索的关键字
                    }
                });
    			layer.close(index);
    		},2000);
        }else{
            //layer.msg("请输入搜索的内容");
        	tableIns.reload();
        	layer.close(index);
        }
    });
    
    var users = {};
    
    table.on('checkbox(gridList)', function(obj){
    	if(!$("#isAll").val()){
    	 var checkStatus = table.checkStatus('gridListTable');
    	 $("#lableNum").html('已勾选'+checkStatus.data.additional.length+'个企业');
    	 var num1 = 0;
     	for (var key in users) {
     		if( users[key]){
             num1 += parseInt(users[key]);  
     	}
         }
     	 if(num1>$("#lableNum").html().substring($("#lableNum").html().indexOf('选')+1,$("#lableNum").html().indexOf('个'))){
     		 for (var key in users) {
     	    		if( users[key]){
     	    			 delete users[key];  
     	    	}
     	        }
     		 table.reload('userListTable', {});
     	 }
    	}
  	});
    
    //用户列表
    var tableMen = table.render({
        elem: '#userList',
        method: 'post',
        url : '../user/allmenmber',
        cellMinWidth : 95,
        page : false,
        initSort: {
            field: 'createTime' //排序字段，对应 cols 设定的各字段名
            ,type: 'asc' //排序方式  asc: 升序、desc: 降序、null: 默认排序
        },
        id : "userListTable",
        cols : [[
        	{field: 'id', title: 'ID', minWidth:50, align:"center"},
        	{field: 'employeeId', title: '工号', minWidth:100, align:"center"},
            {field: 'loginName', title: '用户名', minWidth:100, align:"center"},
            {field: 'name', title: '姓名', minWidth:100, align:"center"},
            {field: 'createTime', title: '创建时间', minWidth:150, align:"center"},
            {field: 'sex', minWidth:50, title: '用户性别', align:'center',templet:function(d){
            	return d.sex == "0" ? "男" : "女";
            }},
            {field: 'age', minWidth:50, title: '年龄', align:'center'},
            {field: 'phone', title: '电话', align:'center'},
            {field: 'rolesList', title: '角色', align:'center'},
            {field: 'userType', title: '用户类型', align:'center',templet:function(d){
                if(d.userType == "0"){
                    return "管理员";
                }else if(d.userType == "1"){
                    return "用户";
                }else{
                    return "未知类型";
                }
            }},
            {field: 'status', title: '用户状态',  align:'center',templet:function(d){
            	return d.status == "0" ? "正常使用" : "限制使用";
            }},
            {title: '分配数量', fixed:"right",align:"center", edit: "text"}
        ]]       
    });
    
    table.on('edit(userList)', function(obj){
    	delete users[obj.data.id];
    	var num = 0;
    	for (var key in users) {
    		if( users[key]){
            num += parseInt(users[key]);  
    	}
        }
    	 num += parseInt(obj.value);
    	 if(num>$("#lableNum").html().substring($("#lableNum").html().indexOf('选')+1,$("#lableNum").html().indexOf('个'))){
    		 for (var key in users) {
    	    		if( users[key]){
    	    			 delete users[key];  
    	    	}
    	        }
    		 table.reload('userListTable', {});
    		 layer.alert('分配的企业数量'+num+'大于勾选的企业数量'+$("#lableNum").html().substring($("#lableNum").html().indexOf('选')+1,$("#lableNum").html().indexOf('个'))+',请重新分配!');
    	 }else{
    		 if(obj.value){
        		 users[obj.data.id] = obj.value;
             }else{
            	 delete users[obj.data.id];
             }
    	 }
    	});

    //格式化时间
    function filterTime(val){
        if(val < 10){
            return "0" + val;
        }else{
            return val;
        }
    }
    //定时发布
    var time = new Date();
    var submitTime = time.getFullYear()+'-'+filterTime(time.getMonth()+1)+'-'+filterTime(time.getDate())+' '+filterTime(time.getHours())+':'+filterTime(time.getMinutes())+':'+filterTime(time.getSeconds());
    
  //列表操作
    table.on('tool(gridList)', function(obj){
        var layEvent = obj.event,
            data = obj.data;
       if(layEvent === 'del'){ //删除
    	var olddata = table.cache.gridListTable;
    	olddata.splice(obj.tr.data('index'),1);
    	tableIns.reload({data:olddata});
        }
    });
    
     form.on('radio(choosemode)', function chooseMode(data){
    	if (data.value == "hm"){
    		$('#usertable').show();   		
    	}else{
    		$('#usertable').hide();
    	}
    })
    
    form.on("submit(addbatch)",function(data){
    	console.log($("#isAll").val());
    	var num = 0;
        var flag = true;
    	for (var key in users) {  
    		if( users[key]){
            num += parseInt(users[key]);  
    	}
    	}
    	if($("#lableNum").html().substring($("#lableNum").html().indexOf('选')+1,$("#lableNum").html().indexOf('个'))==0){
    		layer.alert('未选择企业!');
    		flag = false;
    	}else if(($("input[name='way']:checked").val()=='hm')&&num!=$("#lableNum").html().substring($("#lableNum").html().indexOf('选')+1,$("#lableNum").html().indexOf('个'))){
	 		layer.alert('选择的企业数量'+num+'与分配总数'+$("#lableNum").html().substring($("#lableNum").html().indexOf('选')+1,$("#lableNum").html().indexOf('个'))+'不符!');
	 		flag = false;
	 	}
    	if(flag){	 	
        //弹出loading
        var index = layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});
        setTimeout(function(){
        	$.ajax({
    			type : "POST",
    			url : "../allocatedlist/addBatch",
    			data : {
    				"tasks" : JSON.stringify(table.checkStatus('gridListTable').data.additional),
    				"users" : JSON.stringify(users),
    			    "way" : $("input[name='way']:checked").val(),
    			    "orderId" : parent.$('#orderId').val(),
    			    "companyName" : $(".searchVal").val(),
    				"type" : $("#type").find("option:selected").text(),
    				"develop" : $("#develop").find("option:selected").val(),
    				"industry" : $("#industry").find("option:selected").text(),
    				"scale" : $("#scale").find("option:selected").text(),
    				"isAll" : $("#isAll").val()
    			},
    			dataType : "json",
    			success : function(jsonObject) {
    				top.layer.close(index);
    	            top.layer.msg("任务添加成功！");
    	            layer.closeAll("iframe");
    	            //刷新父页面
    	            parent.location.reload();
    			}
    		});
        },2000);
        return false;
	 	}
    });
})